<template>
  <div class="running-status H100">
    <div>
      <el-tabs type="border-card" v-model="runtimeName" @tab-click="runtimeClick"
        style="flex: 1; height: 800px; margin-bottom: 5px">
        <el-tab-pane label="从机实时状态" name="slave">
          <!-- tabs多时，可以自己新建组件，免重复代码   -->
          <el-tabs type="card" v-model="thingsType" @tab-click="handleClick"
            style=" margin-top: -1px; height: 800px; margin-bottom: 5px">
            <el-tab-pane label="属性上报" name="prop">
              <el-main v-loading="loading" style="position: relative" class="H100">
                <el-row :gutter="20" class="row-list">
                  <el-col :xs="24" :sm="12" :md="12" :lg="8" :xl="6" v-for="(item, index) in runningData" :key="index"
                    style="margin-bottom: 10px">
                    <el-card style="padding: 0px; height: 90px">
                      <div class="head">
                        <div class="title">{{ item.name }}({{ item.id }})</div>
                        <div class="name">
                          <span style="color: #0f73ee">{{ item.value }}</span>
                          <span v-if="item.datatype.unit">{{ item.datatype.unit || item.datatype.unitName }}</span>
                        </div>
                      </div>
                      <div>时间：{{ item.ts }}</div>
                    </el-card>
                  </el-col>
                </el-row>
              </el-main>
            </el-tab-pane>
            <el-tab-pane label="服务下发" name="function">
              <el-main v-loading="loading" style="position: relative" class="H100">
                <el-row :gutter="20" class="row-list">
                  <el-col ::xs="17" :sm="12" :md="12" :lg="8" :xl="6" v-for="(item, index) in functionData" :key="index"
                    style="margin-bottom: 10px">
                    <el-card shadow="hover" class="elcard" style="height: 90px">
                      <div class="head">
                        <div class="title">
                          {{ item.name }}
                        </div>
                        <div class="name">
                          <span style="color: #0f73ee">{{ item.value }}</span>
                          <span v-if="item.datatype.unit">{{ item.datatype.unit }}</span>
                          <el-button type="primary" plain icon="el-icon-s-promotion" size="mini"
                            style="float: right; margin-right: -5px; padding: 3px 5px"
                            @click.stop="editFunc(item)">发送</el-button>
                        </div>
                      </div>
                      <div>
                        <span>时间：{{ item.ts }}</span>
                      </div>
                    </el-card>
                  </el-col>
                  <el-col ::xs="7" :sm="12" :md="12" :lg="8" :xl="6" class="phone-main">
                    <div class="phone">
                      <div class="phone-container">
                        <div class="phone-title">设 备 指 令</div>
                        <div class="log-content" ref="logContent">
                          <el-scrollbar style="height: 100%" ref="scrollContent">
                            <ul v-for="(item, index) in logList" :key="index">
                              <li>
                                <a href="#" style="float: left; text-align: left">
                                  <div class="time">{{ item.createTime }}</div>
                                  <div class="spa">
                                    <span class="lable-s1">服务下发:</span>
                                    {{ item.modelName }}
                                  </div>
                                </a>
                                <a href="#" style="float: right; text-align: right">
                                  <div class="time">{{ item.replyTime }}</div>
                                  <div :class="{ fail: item.resultCode == 201, wait: item.resultCode == 203 }">
                                    <span class="lable-s1">设备应答:</span>
                                    {{ item.showValue }}
                                  </div>
                                </a>
                              </li>
                            </ul>
                          </el-scrollbar>
                        </div>
                      </div>
                    </div>
                  </el-col>
                </el-row>
                <el-empty description="暂无数据" v-show="runningData.length == 0"></el-empty>
              </el-main>
            </el-tab-pane>
            <el-tab-pane disabled name="slave">
              <span slot="label" style="margin-left: 50px">
                <span ref="statusTitle" style="color: #409eff; margin-right: 30px">{{ title }}</span>
                <el-select v-model="params.slaveId" placeholder="请选择设备从机" @change="selectSlave" size="mini">
                  <el-option v-for="slave in slaveList" :key="slave.slaveId"
                    :label="`${slave.deviceName}   (${slave.slaveId})`" :value="slave.slaveId"></el-option>
                </el-select>
              </span>
            </el-tab-pane>
          </el-tabs>

        </el-tab-pane>
        <el-tab-pane label="网关实时状态" name="gateway">
          <el-row :gutter="120">
            <el-col :xs="24" :sm="24" :md="24" :lg="14" :xl="10" style="margin-bottom: 50px">
              <el-descriptions :column="1" border style="margin-bottom: 50px">
                <!-- 设备模式-->
                <el-descriptions-item :labelStyle="statusColor">
                  <template slot="label">
                    <i class="el-icon-menu"></i>
                    设备模式
                  </template>
                  <el-link :underline="false" style="line-height: 28px; font-size: 16px; padding-right: 10px">{{ title
                    }}</el-link>
                </el-descriptions-item>

                <!-- 设备物模型-->
                <el-descriptions-item v-for="(item, index) in this.deviceInfo.thingsModels" :key="index"
                  :labelStyle="statusColor">
                  <template slot="label">
                    <i class="el-icon-open"></i>
                    {{ item.name }}
                  </template>
                  <div v-if="item.datatype.type == 'bool'">
                    <el-switch v-model="item.shadow" @change="mqttPublish(deviceInfo, item)" active-text=""
                      inactive-text="" active-value="1" inactive-value="0" style="min-width: 100px"
                      :disabled="shadowUnEnable || item.isReadonly == 1" />
                  </div>
                  <div v-if="item.datatype.type == 'enum'">
                    <div v-if="item.datatype.showWay && item.datatype.showWay == 'button'">
                      <el-button style="margin: 5px" size="mini"
                        @click="enumButtonClick(deviceInfo, item, subItem.value)"
                        v-for="subItem in item.datatype.enumList" :key="subItem.value"
                        :disabled="shadowUnEnable || item.isReadonly == 1">
                        {{ subItem.text }}
                      </el-button>
                    </div>
                    <el-select v-else v-model="item.shadow" placeholder="请选择" @change="mqttPublish(deviceInfo, item)"
                      :disabled="shadowUnEnable || item.isReadonly == 1">
                      <el-option v-for="subItem in item.datatype.enumList" :key="subItem.value" :label="subItem.text"
                        :value="subItem.value" />
                    </el-select>
                  </div>
                  <div v-if="item.datatype.type == 'string'">
                    <el-input v-model="item.shadow"
                      :placeholder="'请输入字符串 ' + (item.datatype.unit ? '，单位：' + item.datatype.unit : '')"
                      :disabled="shadowUnEnable || item.isReadonly == 1">
                      <el-button slot="append" icon="el-icon-s-promotion" @click="mqttPublish(deviceInfo, item)"
                        style="font-size: 20px" title="指令发送" v-if="!shadowUnEnable && item.isReadonly == 0"></el-button>
                    </el-input>
                  </div>
                  <div v-if="item.datatype.type == 'decimal'">
                    <div style="width: 80%; float: left">
                      <el-slider v-model="item.shadow" :min="item.datatype.min" :max="item.datatype.max"
                        :step="item.datatype.step" :format-tooltip="(x) => x + ' ' + item.datatype.unit"
                        :disabled="shadowUnEnable || item.isReadonly == 1"></el-slider>
                    </div>
                    <div style="width: 20%; float: left">
                      <el-button icon="el-icon-s-promotion" type="info" @click="mqttPublish(deviceInfo, item)"
                        style="font-size: 16px; padding: 1px 8px; margin: 2px 0 0 5px; border-radius: 3px" title="指令发送"
                        v-if="!shadowUnEnable && item.isReadonly == 0"></el-button>
                    </div>
                  </div>
                  <div v-if="item.datatype.type == 'integer'">
                    <div style="width: 80%; float: left">
                      <el-slider v-model="item.shadow" :min="item.datatype.min" :max="item.datatype.max"
                        :step="item.datatype.step" :format-tooltip="(x) => x + ' ' + item.datatype.unit"
                        :disabled="shadowUnEnable || item.isReadonly == 1"></el-slider>
                    </div>
                    <div style="width: 20%; float: left">
                      <el-button icon="el-icon-s-promotion" type="info" @click="mqttPublish(deviceInfo, item)"
                        style="font-size: 16px; padding: 1px 8px; margin: 4px 0 0 10px; border-radius: 3px" title="指令发送"
                        v-if="!shadowUnEnable && item.isReadonly == 0"></el-button>
                    </div>
                  </div>
                </el-descriptions-item>
              </el-descriptions>

              <!---设备状态(影子模式，value值不会更新)-->
              <el-descriptions :column="1" border size="mini" v-if="deviceInfo.isShadow == 1 && deviceInfo.status != 3">
                <template slot="title">
                  <span style="font-size: 14px; color: #606266">设备离线时状态</span>
                </template>

                <!-- 设备物模型-->
                <el-descriptions-item v-for="(item, index) in deviceInfo.thingsModels" :key="index">
                  <template slot="label">
                    <i class="el-icon-open"></i>
                    {{ item.name }}
                  </template>
                  <div v-if="item.datatype.type == 'bool'">
                    <el-switch v-model="item.value" @change="mqttPublish(deviceInfo, item)" active-text=""
                      inactive-text="" active-value="1" inactive-value="0" style="min-width: 100px" disabled />
                  </div>
                  <div v-if="item.datatype.type == 'enum'">
                    <div v-if="item.datatype.showWay && item.datatype.showWay == 'button'">
                      <el-button style="margin: 5px" size="mini" disabled v-for="subItem in item.datatype.enumList"
                        :key="subItem.value">{{ subItem.text }}</el-button>
                    </div>
                    <el-select v-else v-model="item.value" placeholder="请选择" @change="mqttPublish(deviceInfo, item)"
                      disabled size="mini">
                      <el-option v-for="subItem in item.datatype.enumList" :key="subItem.value" :label="subItem.text"
                        :value="subItem.value" />
                    </el-select>
                  </div>
                  <div v-if="item.datatype.type == 'string'">
                    <el-input v-model="item.value" placeholder="请输入字符串" disabled size="mini"></el-input>
                  </div>
                  <div v-if="item.datatype.type == 'decimal'">
                    <el-input v-model="item.value" type="number" placeholder="请输入小数 " disabled size="mini"></el-input>
                  </div>
                  <div v-if="item.datatype.type == 'integer'">
                    <el-input v-model="item.value" type="integer" placeholder="请输入整数 " disabled size="mini"></el-input>
                  </div>
                  <div v-if="item.datatype.type == 'object'">
                    <el-descriptions :column="1" size="mini" border>
                      <el-descriptions-item v-for="(param, index) in item.datatype.params" :key="index"
                        :label="param.name">
                        <div v-if="param.datatype.type == 'bool'">
                          <el-switch v-model="param.value" size="mini" @change="mqttPublish(deviceInfo, param)"
                            active-text="" inactive-text="" active-value="1" inactive-value="0" style="min-width: 100px"
                            disabled />
                        </div>
                        <div v-if="param.datatype.type == 'enum'">
                          <el-select v-model="param.value" placeholder="请选择" @change="mqttPublish(deviceInfo, param)"
                            disabled size="mini">
                            <el-option v-for="subItem in param.datatype.enumList" :key="subItem.value"
                              :label="subItem.text" :value="subItem.value" />
                          </el-select>
                        </div>
                        <div v-if="param.datatype.type == 'string'">
                          <el-input v-model="param.value" placeholder="请输入字符串" disabled size="mini"></el-input>
                        </div>
                        <div v-if="param.datatype.type == 'decimal'">
                          <el-input v-model="param.value" type="number" placeholder="请输入小数 " disabled
                            size="mini"></el-input>
                        </div>
                        <div v-if="param.datatype.type == 'integer'">
                          <el-input v-model="param.value" type="integer" placeholder="请输入整数 " disabled
                            size="mini"></el-input>
                        </div>
                      </el-descriptions-item>
                    </el-descriptions>
                  </div>
                  <div v-if="item.datatype.type == 'array'">
                    <el-descriptions :column="1" size="mini" border v-if="item.datatype.arrayType != 'object'">
                      <el-descriptions-item v-for="(model, index) in item.datatype.arrayModel" :key="index"
                        :label="item.name + (index + 1)">
                        <div v-if="item.datatype.arrayType == 'string'">
                          <el-input v-model="model.value" placeholder="请输入字符串" size="mini" disabled></el-input>
                        </div>
                        <div v-if="item.datatype.arrayType == 'decimal'">
                          <el-input v-model="model.value" type="number" placeholder="请输入小数 " size="mini"
                            disabled></el-input>
                        </div>
                        <div v-if="item.datatype.arrayType == 'integer'">
                          <el-input v-model="model.value" type="integer" placeholder="请输入整数 " size="mini"
                            disabled></el-input>
                        </div>
                      </el-descriptions-item>
                    </el-descriptions>
                    <el-collapse v-if="item.datatype.arrayType == 'object'">
                      <el-collapse-item v-for="(arrayParam, index) in item.datatype.arrayParams" :key="index">
                        <template slot="title">
                          <span style="color: #666">
                            <i class="el-icon-tickets"></i>
                            {{ item.name + (index + 1) }}
                          </span>
                        </template>
                        <el-descriptions :column="1" size="mini" border>
                          <el-descriptions-item v-for="(param, index) in arrayParam" :key="index" :label="param.name">
                            <div v-if="param.datatype.type == 'bool'">
                              <el-switch v-model="param.value" @change="mqttPublish(deviceInfo, param)" active-text=""
                                inactive-text="" active-value="1" inactive-value="0" style="min-width: 100px"
                                disabled />
                            </div>
                            <div v-if="param.datatype.type == 'enum'">
                              <el-select v-model="param.value" placeholder="请选择"
                                @change="mqttPublish(deviceInfo, param)" disabled size="mini">
                                <el-option v-for="subItem in param.datatype.enumList" :key="subItem.value"
                                  :label="subItem.text" :value="subItem.value" />
                              </el-select>
                            </div>
                            <div v-if="param.datatype.type == 'string'">
                              <el-input v-model="param.value" placeholder="请输入字符串" disabled size="mini"></el-input>
                            </div>
                            <div v-if="param.datatype.type == 'decimal'">
                              <el-input v-model="param.value" type="number" placeholder="请输入小数 " disabled
                                size="mini"></el-input>
                            </div>
                            <div v-if="param.datatype.type == 'integer'">
                              <el-input v-model="param.value" type="integer" placeholder="请输入整数 " disabled
                                size="mini"></el-input>
                            </div>
                          </el-descriptions-item>
                        </el-descriptions>
                      </el-collapse-item>
                    </el-collapse>
                  </div>
                </el-descriptions-item>
              </el-descriptions>
            </el-col>

          </el-row>
        </el-tab-pane>
      </el-tabs>

    </div>

    <el-dialog title="服务调用" :visible.sync="dialogValue" label-width="200px">
      <el-form v-model="from" size="mini" style="height: 100%; padding: 0 20px">
        <el-form-item :label="from.name" label-width="180px">
          <el-input v-model="from.shadow" type="number" @input="justicNumber()"
            v-if="from.datatype.type == 'integer' || from.datatype.type == 'decimal' || from.datatype.type == 'string'"
            style="width: 50%"></el-input>
          <el-select v-if="from.datatype.type == 'enum'" v-model="from.shadow" @change="changeSelect()">
            <el-option v-for="option in from.datatype.enumList" :key="option.value" :label="option.text"
              :value="option.value"></el-option>
          </el-select>
          <el-switch v-if="from.datatype.type === 'bool'" v-model="from.shadow" active-value="1" inactive-value="0"
            inline-prompt />
          <span
            v-if="(from.datatype.type == 'integer' || from.datatype.type == 'decimal') && from.datatype.type.unit && from.datatype.type.unit != 'un' && from.datatype.type.unit != '/'">（{{
              from.unit }}）</span>
          <div v-if="from.datatype.type == 'integer' || from.datatype.type == 'decimal'" class="range">
            (数据范围:{{ from.datatype.max == 'null' ? (from.datatype.type == 'bool' ? 0 : '') : from.datatype.min }} ~ {{
              from.datatype.max == 'null' ? (from.datatype.type == 'bool' ? 1 : '') : from.datatype.max }})
          </div>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogValue = false">取消</el-button>
        <el-button type="primary" @click="sendService" :loading="btnLoading" :disabled="!canSend">确认</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { serviceInvoke, funcLog } from '@/api/iot/runstatus';
import { formatDate2 } from '@/utils/index';
import { listByPid } from '@/api/iot/salve';
import { getDeviceRunningStatus } from '@/api/iot/device';
import { listSimulateLog } from '@/api/iot/simulate';

const INTEGER = 'integer';
const DECIMAL = 'decimal';
const BOOL = 'bool';
const ENUM = 'enum';

export default {
  name: 'realTime-status',
  props: {
    device: {
      type: Object,
      default: null,
    },
  },
  data() {
    return {
      // 未启用设备影子
      shadowUnEnable: false,
      // 控制项标题背景
      statusColor: {
        background: '#67C23A',
        color: '#fff',
        minWidth: '100px',
      },
      /**设备模拟消息列表**/
      messageList: [],
      /**设备模拟发送消息表单**/
      simulateForm: {},
      deviceInfo: {}, // 设备信息
      dialogValue: false, // 查看详情弹框
      gridData: [], // 事件数据
      groupId: 1,
      treeData: [],
      runningData: [], // 实时状态列表
      gatewayData: [],
      functionData: [],
      loading: false,
      debounceGetRuntime: '',
      serialNumber: '',
      slaveId: 1,
      params: {
        serialNumber: undefined,
        type: 1,
      },
      slaveList: [],
      queryParams: {},
      thingsType: 'prop',
      runtimeName: 'slave',
      opationList: [], // 指令数值数组
      funVal: {},
      canSend: false, //是否可以下发，主要判断数值在不在范围
      functionName: {},
      btnLoading: false,
      logList: [],
      showValue: '',
      from: {
        datatype: {
          type: '',
        },
      },
      title: '在线模式',
    };
  },

  created() { },

  watch: {
    device: {
      handler(newVal) {
        if (newVal && newVal.serialNumber) {
          this.params.serialNumber = newVal.serialNumber;
          this.serialNumber = newVal.serialNumber;
          this.params.productId = newVal.productId;
          this.params.slaveId = newVal.slaveId;
          this.params.deviceId = newVal.deviceId;
          this.deviceInfo = newVal;
          this.updateDeviceStatus(this.deviceInfo);
          this.slaveList = newVal.subDeviceList;
          this.getSlaveList(this.deviceInfo);
          this.$busEvent.$on('updateData', (params) => {
            if (params.data && params.data[0].remark) {
              this.getDeviceFuncLog();
              params.data[0].ts = params.data[0].remark;
            }
            this.updateData(params);
          });
          this.$busEvent.$on('updateLog', (params) => {
            this.getDeviceFuncLog();
          });
          this.mqttCallback();
        }
      }
    },
  },
  methods: {
    /** qos改变事件 **/
    qosChange(data) { },
    /** 载体改变事件 **/
    payloadTypeChange(data) { },
    /** 获取当前时间 **/
    getTime() {
      let date = new Date();
      let y = date.getFullYear();
      let m = date.getMonth() + 1;
      let d = date.getDate();
      let H = date.getHours();
      let mm = date.getMinutes();
      let s = date.getSeconds();
      m = m < 10 ? '0' + m : m;
      d = d < 10 ? '0' + d : d;
      H = H < 10 ? '0' + H : H;
      return y + '-' + m + '-' + d + ' ' + H + ':' + mm + ':' + s;
    },

    /*获取运行状态*/
    getRuntimeStatus() {
      getDeviceRunningStatus(this.params).then((response) => {
        this.runningData = response.data.thingsModels;
        this.runningData.forEach((item) => {
          if (item.datatype.type == 'enum') {
            item.datatype.enumList.forEach((val) => {
              if (val.value == item.value) {
                item.value = val.text;
              }
            });
          } else if (item.datatype.type == 'bool') {
            item.value = item.value == 0 ? item.falseText : item.trueText;
          }
        });
        //筛选读写物模型
        this.functionData = this.runningData.filter((item) => item.isReadonly == 0);
      });
    },

    getGateway() {
      getDeviceRunningStatus(this.params).then((response) => {
        this.deviceInfo.thingsModels = response.data.thingsModels;
      });
    },

    /**根据产品id获取从机列表*/
    getSlaveList() {
      this.getRuntimeStatus();
      this.getDeviceFuncLog();
    },
    /*选择从机*/
    selectSlave() {
      this.params.serialNumber = this.serialNumber + '_' + this.params.slaveId;
      this.getRuntimeStatus();
    },
    /*tabs切换*/
    handleClick() {
      if (this.thingsType === 'prop') {
        this.params.type = 1;
      } else if (this.thingsType === 'function') {
        this.params.type = 2;
        //筛选读写物模型
        this.functionData = this.runningData.filter((item) => item.isReadonly == 0);
      }
    },
    //切换实时状态
    runtimeClick() {
      if (this.runtimeName === 'gateway') {
        this.params.serialNumber = this.serialNumber;
        this.slaveId = this.params.slaveId;
        this.params.slaveId = undefined;
        this.getGateway();
      } else {
        this.params.serialNumber = this.serialNumber + '_' + this.slaveId;
        this.params.slaveId = this.slaveId;
        this.getRuntimeStatus();
      }
    },
    // 更新参数值
    updateParam(data) { },
    //指令下发
    editFunc(item) {
      this.dialogValue = true;
      this.canSend = true;
      this.funVal = {};
      this.getValueName(item);
      this.from = item;
      console.log(this.runningData);
    },


    /** 更新设备状态 */
    updateDeviceStatus(device) {
      if (device.status == 3) {
        this.statusColor.background = '#12d09f';
        this.title = '在线模式';
      } else {
        if (device.isShadow == 1) {
          this.statusColor.background = '#409EFF';
          this.title = '影子模式';
        } else {
          this.statusColor.background = '#909399';
          this.title = '离线模式';
          this.shadowUnEnable = true;
        }
      }
      this.$emit('statusEvent', this.deviceInfo.status);
    },

    // 解析值
    getValueName(item) {
      this.funVal[item.id] = item.value;
    },
    // 发送指令
    sendService() {
      console.log('下发指令', this.from.shadow);
      try {
        this.funVal[this.from.id] = this.from.shadow;
        const data = {
          serialNumber: this.serialNumber,
          productId: this.params.productId,
          remoteCommand: this.funVal,
          identifier: this.from.id,
          slaveId: this.params.slaveId,
          modelName: this.from.name,
          isShadow: this.device.status != 3,
          type: this.from.type,
        };
        serviceInvoke(data).then((response) => {
          if (response.code == 200) {
            this.$message({
              type: 'success',
              message: '服务调用成功!',
            });
            this.getDeviceFuncLog();
          }
        });
      } finally {
        this.dialogValue = false;
      }
    },

    //发送指令
    mqttPublish(device, model) {
      const command = {};
      command[model.id] = model.shadow;
      const data = {
        serialNumber: device.serialNumber,
        productId: device.productId,
        remoteCommand: command,
        identifier: model.id,
        modelName: model.name,
        isShadow: device.status != 3,
        type: model.type,
      };
      serviceInvoke(data).then((response) => {
        if (response.code === 200) {
          this.$message({
            type: 'success',
            message: '服务调用成功!',
          });
        }
      });
    },

    getShowValue(value) {
      switch (this.from.datatype.type) {
        case ENUM:
          const list = this.from.datatype.enumList;
          list.forEach((m) => {
            if (m.value === value) {
              this.showValue = m.text;
            }
          });
          break;
        case INTEGER:
        case DECIMAL:
          this.showValue = value;
        case BOOL:
          this.showValue = value == 1 ? this.from.datatype.trueText : this.from.datatype.falseText;
          break;
      }
    },

    //下拉选择修改触发
    changeSelect() {
      this.$forceUpdate();
    },

    //判断输入是否超过范围
    justicNumber() {
      this.canSend = true;
      if (this.from.datatype.max < this.funVal[this.from.identity] || this.from.datatype.min > this.funVal[this.from.identity]) {
        this.canSend = false;
        return true;
      }
      this.$forceUpdate();
    },

    //  获取设备服务下发日志
    getDeviceFuncLog() {
      const params = {
        serialNumber: this.serialNumber,
      };
      console.log("params --", params)
      funcLog(params).then((response) => {
        this.logList = response.rows;
      });
    },
    updateData(msg) {
      if (msg.data) {
        msg.data.forEach((d) => {
          this.runningData.some((old, index) => {
            if (d.slaveId === old.slaveId && d.id == old.id) {
              const template = this.runningData[index];
              template.ts = d.ts;
              template.value = d.value;
              if (old.datatype.type == 'enum') {
                old.datatype.enumList.forEach((val) => {
                  if (val.value == template.value) {
                    template.value = val.text;
                  }
                });
              } else if (old.datatype.type == 'bool') {
                template.value = template.value == 0 ? old.datatype.falseText : old.datatype.trueText;
              }
              this.$set(this.runningData, index, template);
              return true;
            }
          });
        });
      }
    },

    /* Mqtt回调处理 */
    mqttCallback() {
      this.$mqttTool.client.on('message', (topic, message, buffer) => {
        let topics = topic.split('/');
        let productId = topics[1];
        let deviceNum = topics[2];
        message = JSON.parse(message.toString());
        if (!message) {
          return;
        }
        if (topics[3] == 'status') {
          console.log('接收到【设备状态-运行】主题3：', topic);
          console.log('接收到【设备状态-运行】内容3：', message);
          // 更新列表中设备的状态
          if (this.deviceInfo.serialNumber == deviceNum) {
            this.deviceInfo.status = message.status;
            this.deviceInfo.isShadow = message.isShadow;
            this.deviceInfo.rssi = message.rssi;
            this.updateDeviceStatus(this.deviceInfo);
          }
        }
        //兼容设备回复
        if (topics[4] == 'reply') {
          this.$modal.notifySuccess(message);
        }
        if (topic.endsWith('ws/service')) {
          console.log('接收到【物模型】主题1：', topic);
          console.log('接收到【物模型】内容1：', message);
          // 更新列表中设备的属性
          if (this.deviceInfo.serialNumber == deviceNum) {
            for (let j = 0; j < message.length; j++) {
              let isComplete = false;
              // 设备状态
              for (let k = 0; k < this.deviceInfo.thingsModels.length && !isComplete; k++) {
                if (this.deviceInfo.thingsModels[k].id == message[j].id) {
                  // 普通类型(小数/整数/字符串/布尔/枚举)
                  if (this.deviceInfo.thingsModels[k].datatype.type == 'decimal' || this.deviceInfo.thingsModels[k].datatype.type == 'integer') {
                    this.deviceInfo.thingsModels[k].shadow = Number(message[j].value);
                  } else {
                    this.deviceInfo.thingsModels[k].shadow = message[j].value;
                  }
                  isComplete = true;
                  break;
                } else if (this.deviceInfo.thingsModels[k].datatype.type == 'object') {
                  // 对象类型
                  for (let n = 0; n < this.deviceInfo.thingsModels[k].datatype.params.length; n++) {
                    if (this.deviceInfo.thingsModels[k].datatype.params[n].id == message[j].id) {
                      this.deviceInfo.thingsModels[k].datatype.params[n].shadow = message[j].value;
                      isComplete = true;
                      break;
                    }
                  }
                } else if (this.deviceInfo.thingsModels[k].datatype.type == 'array') {
                  // 数组类型
                  if (this.deviceInfo.thingsModels[k].datatype.arrayType == 'object') {
                    // 1.对象类型数组,id为数组中一个元素,例如：array_01_gateway_temperature
                    if (String(message[j].id).indexOf('array_') == 0) {
                      for (let n = 0; n < this.deviceInfo.thingsModels[k].datatype.arrayParams.length; n++) {
                        for (let m = 0; m < this.deviceInfo.thingsModels[k].datatype.arrayParams[n].length; m++) {
                          if (this.deviceInfo.thingsModels[k].datatype.arrayParams[n][m].id == message[j].id) {
                            this.deviceInfo.thingsModels[k].datatype.arrayParams[n][m].shadow = message[j].value;
                            isComplete = true;
                            break;
                          }
                        }
                        if (isComplete) {
                          break;
                        }
                      }
                    } else {
                      // 2.对象类型数组，例如：gateway_temperature,消息ID添加前缀后匹配
                      for (let n = 0; n < this.deviceInfo.thingsModels[k].datatype.arrayParams.length; n++) {
                        for (let m = 0; m < this.deviceInfo.thingsModels[k].datatype.arrayParams[n].length; m++) {
                          let index = n > 9 ? String(n) : '0' + k;
                          let prefix = 'array_' + index + '_';
                          if (this.deviceInfo.thingsModels[k].datatype.arrayParams[n][m].id == prefix + message[j].id) {
                            this.deviceInfo.thingsModels[k].datatype.arrayParams[n][m].shadow = message[j].value;
                            isComplete = true;
                          }
                        }
                        if (isComplete) {
                          break;
                        }
                      }
                    }
                  } else {
                    // 整数、小数和字符串类型数组
                    for (let n = 0; n < this.deviceInfo.thingsModels[k].datatype.arrayModel.length; n++) {
                      if (this.deviceInfo.thingsModels[k].datatype.arrayModel[n].id == message[j].id) {
                        this.deviceInfo.thingsModels[k].datatype.arrayModel[n].shadow = message[j].value;
                        isComplete = true;
                        break;
                      }
                    }
                  }
                }
              }
              // 图表数据
              for (let k = 0; k < this.deviceInfo.chartList.length; k++) {
                if (this.deviceInfo.chartList[k].id.indexOf('array_') == 0) {
                  // 数组类型匹配,例如：array_00_gateway_temperature
                  if (this.deviceInfo.chartList[k].id == message[j].id) {
                    // let shadows = message[j].value.split(",");
                    this.deviceInfo.chartList[k].shadow = message[j].value;
                    // 更新图表
                    for (let m = 0; m < this.monitorChart.length; m++) {
                      if (message[j].id == this.monitorChart[m].data.id) {
                        let data = [
                          {
                            value: message[j].value,
                            name: this.monitorChart[m].data.name,
                          },
                        ];
                        this.monitorChart[m].chart.setOption({
                          series: [
                            {
                              data: data,
                            },
                          ],
                        });
                        break;
                      }
                    }
                  }
                } else {
                  // 普通类型匹配
                  if (this.deviceInfo.chartList[k].id == message[j].id) {
                    this.deviceInfo.chartList[k].shadow = message[j].value;
                    // 更新图表
                    for (let m = 0; m < this.monitorChart.length; m++) {
                      if (message[j].id == this.monitorChart[m].data.id) {
                        isComplete = true;
                        let data = [
                          {
                            value: message[j].value,
                            name: this.monitorChart[m].data.name,
                          },
                        ];
                        this.monitorChart[m].chart.setOption({
                          series: [
                            {
                              data: data,
                            },
                          ],
                        });
                        break;
                      }
                    }
                  }
                }
                if (isComplete) {
                  break;
                }
              }
            }
          }
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.phone-main {
  float: right;
}

.phone {
  height: 729px;
  width: 370px;
  background-image: url('../../../assets/images/phone.png');
  background-size: cover;
}

.phone-container {
  height: 618px;
  width: 343px;
  position: relative;
  top: 46px;
  left: 12px;
  background-color: #fff;

  .phone-title {
    line-height: 40px;
    color: #fff;
    background-color: #007aff;
    text-align: center;
  }

  .messageContent {
    height: 440px;
    overflow-y: scroll;
    word-wrap: break-word;
    padding: 6px 0;
    color: #fff;
  }

  .messageBottom {
    height: 150px;
    position: absolute;
    bottom: 0;
    width: 100%;
    background-color: #eef3f7;
    padding: 5px;
    border-top: 1px solid #d2dae1;
  }

  .messageReceive {
    float: left;
    background-color: #409eff;
    border-radius: 6px;
    padding: 10px;
    width: 70%;
    font-size: 12px;
    margin-bottom: 15px;
    border-style: dotted;
  }

  .messageSend {
    float: right;
    background-color: #13ce66;
    border-radius: 10px;
    padding: 10px;
    width: 70%;
    font-size: 12px;
    margin-bottom: 15px;
    border-right-style: double;
  }
}

.log-content {
  padding: 2px;
  height: calc(100% - 44px);
  overflow: auto;

  ul {
    padding: 0;
    margin: 4px 0;
    list-style: none;
  }

  a {
    width: 100%;
    color: #333;
    //border: 1px solid #fff;
    flex-wrap: wrap;
    padding: 5px 5px 1px 5px;
    text-decoration: none;
    font-size: 12px;

    .time {
      font-size: 10px;
      color: gray;
    }

    div {
      color: #1b93e0;

      .lable-s1 {
        color: gray;
      }
    }

    .fail {
      color: #f56c6c;
    }

    .wait {
      color: #909399;
    }
  }
}

.H100 {
  //overflow: hidden;
  margin-left: 10px;
}

.row-list {
  height: calc(100% - 20px);
  height: 700px;
  overflow: auto;
  margin: -20px -20px -20px -30px !important;
  font-size: 12px;
  line-height: 20px;
}

.running-status {
  .select {
    margin-bottom: 15px;
  }

  .edit-class {
    margin-top: 10px;
  }
}
</style>
